package com.ayuan.blog.controller;

import com.alibaba.fastjson.JSON;
import com.ayuan.blog.bean.CommonResponseBean;
import com.ayuan.blog.common.util.CookieUtils;
import com.ayuan.blog.domain.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xiaozhu on 15/12/27.
 */
@Log4j2
public abstract class BaseController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    protected User getCurrentUser(HttpServletRequest request) {
        Cookie cookie = CookieUtils.getCookie(request, "sessionId");
        String userString = stringRedisTemplate.opsForValue().get("userInfo" + cookie.getValue());
        return JSON.parseObject(userString, User.class);
//        return (User) request.getSession().getAttribute("userInfo" + cookie.getValue());
    }

    @ExceptionHandler
    public void handleException(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        log.error(ex.getMessage(), ex);

        try {
            response.getWriter().write(JSON.toJSONString(new CommonResponseBean<Object>(1, "系统异常", null)));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
